<template>
  <div class="home-container">
    <!-- 平台头部横幅 -->
    <div class="banner">
      <div class="banner-content">
        <h1>卒中健康管理平台</h1>
        <p>专业的卒中预防、监测与康复管理系统</p>
        <div class="banner-actions">
          <el-button type="primary" size="large" @click="goToStatistics">开始使用</el-button>
          <el-button size="large">了解更多</el-button>
        </div>
      </div>
    </div>

    <!-- 核心功能模块 -->
    <div class="features-section">
      <div class="container">
        <h2 class="section-title">核心功能</h2>
        <div class="features-grid">
          <el-card class="feature-card clickable" shadow="hover" @click="goToPatientManagement">
            <div class="feature-icon">
              <el-icon><User /></el-icon>
            </div>
            <h3>患者管理</h3>
            <p>全面的患者信息管理和健康数据追踪</p>
          </el-card>
          <el-card class="feature-card clickable" shadow="hover" @click="goToStrokeEvents">
            <div class="feature-icon">
              <el-icon><WarningFilled /></el-icon>
            </div>
            <h3>卒中事件跟踪</h3>
            <p>实时监控和记录卒中相关事件</p>
          </el-card>
          <el-card class="feature-card clickable" shadow="hover" @click="goToTreatmentRecords">
            <div class="feature-icon">
              <el-icon><Operation /></el-icon>
            </div>
            <h3>治疗方案</h3>
            <p>个性化治疗方案制定与执行跟踪</p>
          </el-card>
          <el-card class="feature-card clickable" shadow="hover" @click="goToPolicyDocuments">
            <div class="feature-icon">
              <el-icon><Document /></el-icon>
            </div>
            <h3>政策与指南</h3>
            <p>最新卒中相关政策和医疗指南</p>
          </el-card>
          <el-card class="feature-card" shadow="hover" @click="goToStrokeUserProfile">
            <div class="feature-icon">
              <el-icon><UserFilled /></el-icon>
            </div>
            <h3>用户中心</h3>
            <p>个性化用户信息与医生资源管理</p>
          </el-card>
        </div>
      </div>
    </div>

    <!-- 数据统计卡片 -->
    <div class="stats-section">
      <div class="container">
        <h2 class="section-title">平台数据概览</h2>
        <div class="stats-grid">
          <el-card class="stat-card">
              <div class="stat-icon">
                <el-icon><User /></el-icon>
              </div>
              <div class="stat-number">{{ displayStats.patientCount }}</div>
              <div class="stat-label">患者总数</div>
            </el-card>
            <el-card class="stat-card">
              <div class="stat-icon">
                <el-icon><WarningFilled /></el-icon>
              </div>
              <div class="stat-number">{{ displayStats.strokeEventCount }}</div>
              <div class="stat-label">卒中事件</div>
            </el-card>
            <el-card class="stat-card">
              <div class="stat-icon">
                <el-icon><Operation /></el-icon>
              </div>
              <div class="stat-number">{{ displayStats.treatmentRecordCount }}</div>
              <div class="stat-label">治疗记录</div>
            </el-card>
            <el-card class="stat-card">
              <div class="stat-icon">
                <el-icon><Document /></el-icon>
              </div>
              <div class="stat-number">{{ displayStats.institutionCount }}</div>
              <div class="stat-label">合作机构</div>
            </el-card>
        </div>
      </div>
    </div>

    <!-- 最新动态 -->
    <div class="updates-section">
      <div class="container">
        <h2 class="section-title">最新动态</h2>
        <div class="updates-content">
          <!-- 政策文件 -->
          <div class="updates-column">
            <div class="column-header">
              <h3>政策文件</h3>
              <a href="#" class="view-more">查看更多</a>
            </div>
            <div class="policy-list">
              <div v-for="policy in latestPolicies" :key="policy.id" class="policy-item">
                <div class="policy-meta">
                  <span class="policy-id">文件ID: {{ policy.id }}</span>
                  <span class="policy-date">{{ formatDate(policy.release_date) }}</span>
                </div>
                <h4 class="policy-title">{{ truncateText(policy.title, 30) }}</h4>
              </div>
            </div>
          </div>

          <!-- 新闻公告 -->
          <div class="updates-column">
            <div class="column-header">
              <h3>新闻公告</h3>
              <a href="#" class="view-more">查看更多</a>
            </div>
            <div class="news-list">
              <div v-for="news in latestNews" :key="news.id" class="news-item">
                <div class="news-meta">
                  <span class="news-date">{{ formatDate(news.publish_date) }}</span>
                </div>
                <h4 class="news-title">{{ truncateText(news.title, 30) }}</h4>
              </div>
            </div>
          </div>

          <!-- 热门视频 -->
          <div class="updates-column">
            <div class="column-header">
              <h3>热门视频</h3>
              <a href="#" class="view-more">查看更多</a>
            </div>
            <div class="hot-videos-list">
              <div v-for="(video, index) in hotVideos" :key="video.id" class="hot-video-item">
                <div class="rank-number hot-rank" :class="getRankClass(index)">{{ index + 1 }}</div>
                <h4 class="hot-video-title">{{ video.video_title }}</h4>
                <div class="hot-video-stats">
                  <span><el-icon><StarFilled /></el-icon> {{ video.like_count }}</span>
                  <span><el-icon><View /></el-icon> {{ video.view_count }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 页脚CTA -->
    <div class="cta-section">
      <div class="container">
        <div class="cta-content">
          <h2>开始您的卒中健康管理之旅</h2>
          <p>加入我们的平台，享受专业的健康监测和管理服务</p>
          <el-button type="primary" size="large">立即注册</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue'
import { User, WarningFilled, Operation, Document, StarFilled, View, UserFilled } from '@element-plus/icons-vue'
import { ElCard, ElButton } from 'element-plus'
import { useRouter } from 'vue-router'
import { patientAPI, strokeEventAPI, treatmentAPI } from '../api/index.js'

export default {
  name: 'HomeView',
  components: {
    ElCard,
    ElButton,
    User,
    WarningFilled,
    Operation,
    Document,
    StarFilled,
    View,
    UserFilled
  },
  setup() {
    const router = useRouter()
    // 状态数据
    const stats = ref({
      patientCount: 0,
      strokeEventCount: 0,
      treatmentRecordCount: 0,
      institutionCount: 0
    })
    
    // 显示的统计数据（用于动画效果）
    const displayStats = ref({
      patientCount: 0,
      strokeEventCount: 0,
      treatmentRecordCount: 0,
      institutionCount: 0
    })
    
    // 数字计数动画函数
    const animateCounter = (key, targetValue) => {
      const duration = 1500 // 动画持续时间（毫秒）
      const startTime = Date.now()
      const startValue = displayStats.value[key]
      
      const animate = () => {
        const elapsed = Date.now() - startTime
        const progress = Math.min(elapsed / duration, 1)
        
        // 使用缓动函数使动画更自然
        const easeOutQuad = t => t * (2 - t)
        const currentValue = Math.floor(startValue + (targetValue - startValue) * easeOutQuad(progress))
        
        displayStats.value[key] = currentValue
        
        if (progress < 1) {
          requestAnimationFrame(animate)
        }
      }
      
      animate()
    }
    
    // 获取统计数据
    const fetchStats = async () => {
      try {
        // 获取患者总数
        const patients = await patientAPI.getPatients()
        const newPatientCount = patients.length
        
        // 获取卒中事件总数
        const events = await strokeEventAPI.getEvents()
        const newStrokeEventCount = events.length
        
        // 获取治疗记录总数
        const treatments = await treatmentAPI.getRecords()
        const newTreatmentRecordCount = treatments.length
        
        // 获取医疗机构总数（如果有相关API）
        // 这里保持原有的机构数量，因为没有看到获取机构总数的API
        
        // 更新统计数据
        stats.value = {
          patientCount: newPatientCount,
          strokeEventCount: newStrokeEventCount,
          treatmentRecordCount: newTreatmentRecordCount,
          institutionCount: 48
        }
        
        // 触发数字计数动画
        animateCounter('patientCount', newPatientCount)
        animateCounter('strokeEventCount', newStrokeEventCount)
        animateCounter('treatmentRecordCount', newTreatmentRecordCount)
        animateCounter('institutionCount', 48)
        
        console.log('统计数据更新成功:', stats.value)
      } catch (error) {
        console.error('获取统计数据失败:', error)
        // 如果获取失败，使用默认数据作为后备
        stats.value = {
          patientCount: 1258,
          strokeEventCount: 326,
          treatmentRecordCount: 2890,
          institutionCount: 48
        }
      }
    }

    const latestPolicies = ref([
      { id: 'POL2024001', title: '2024年卒中防治指南更新版', release_date: '2024-03-15' },
      { id: 'POL2024002', title: '脑卒中患者康复管理规范', release_date: '2024-02-20' },
      { id: 'POL2024003', title: '基层医疗机构卒中筛查实施细则', release_date: '2024-01-10' }
    ])

    const latestNews = ref([
      { id: 1, title: '新型脑卒中治疗药物临床试验取得重大突破', publish_date: '2024-04-05' },
      { id: 2, title: '全国卒中中心建设工作会议在京召开', publish_date: '2024-03-28' },
      { id: 3, title: '卒中预防知识宣传活动走进社区', publish_date: '2024-03-20' }
    ])

    const hotVideos = ref([
      { id: 1, video_title: '脑卒中预防知识讲座', like_count: 1254, view_count: 15890 },
      { id: 2, video_title: '康复训练指导：日常生活能力恢复', like_count: 892, view_count: 12345 },
      { id: 3, video_title: '家属照护指南：如何帮助卒中患者', like_count: 756, view_count: 9876 }
    ])

    // 方法
    const formatDate = (dateString) => {
      const date = new Date(dateString)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    }

    const truncateText = (text, maxLength) => {
      if (text.length <= maxLength) return text
      return text.substring(0, maxLength) + '...'
    }

    const getRankClass = (index) => {
      if (index === 0) return 'rank-1'
      if (index === 1) return 'rank-2'
      if (index === 2) return 'rank-3'
      return ''
    }

    // 导航到患者管理页面
    const goToPatientManagement = () => {
      router.push('/patients')
    }
    
    // 导航到卒中事件页面
    const goToStrokeEvents = () => {
      router.push('/stroke-events')
    }
    
    // 导航到治疗记录页面
    const goToTreatmentRecords = () => {
      router.push('/treatments')
    }
    
    // 导航到政策文档页面
    const goToPolicyDocuments = () => {
      router.push('/policy-documents')
    }
    
    // 导航到卒中系统用户中心
    const goToStrokeUserProfile = () => {
      // 默认使用ID为1的用户，实际应用中应该使用当前登录用户的ID
      router.push('/stroke-profile/1')
    }
    
    // 导航到统计页面
    const goToStatistics = () => {
      router.push('/statistics')
    }

    // 组件挂载时的初始化逻辑
    onMounted(() => {
      console.log('HomeView mounted')
      // 首次加载时获取统计数据
      fetchStats()
      
      // 设置定时刷新（每30秒刷新一次）
      refreshInterval = setInterval(() => {
        console.log('定时刷新统计数据')
        fetchStats()
      }, 30000)
    })
    
    // 组件卸载时清理定时器
    onUnmounted(() => {
      if (refreshInterval) {
        clearInterval(refreshInterval)
      }
    })
    
    // 定时器引用
    let refreshInterval = null

    return {
      stats,
      displayStats,
      latestPolicies,
      latestNews,
      hotVideos,
      formatDate,
      truncateText,
      getRankClass,
      goToPatientManagement,
      goToStrokeEvents,
      goToTreatmentRecords,
      goToPolicyDocuments,
      goToStrokeUserProfile,
      goToStatistics
    }
  }
}
</script>

<style scoped>
/* 亮色主题样式 */
.home-container {
  width: 100%;
  background-color: #ffffff;
  min-height: 100vh;
  color: #333333;
}

/* 头部横幅 */
.banner {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  padding: 80px 0;
  text-align: center;
}

.banner-content h1 {
  font-size: 3rem;
  font-weight: 600;
  margin-bottom: 20px;
  color: #333333;
}

.banner-content p {
  font-size: 1.2rem;
  color: #666666;
  margin-bottom: 30px;
}

.banner-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
}

/* 容器样式 */
.container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

/* 通用部分标题 */
.section-title {
  font-size: 2rem;
  font-weight: 600;
  margin-bottom: 40px;
  text-align: center;
  color: #333333;
}

/* 功能模块 */
.features-section {
  padding: 80px 0;
  background-color: #f8f9fa;
}

/* 可点击卡片样式 */
.feature-card.clickable {
  cursor: pointer;
  transition: all 0.3s ease;
}

.feature-card.clickable:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}


.features-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 30px;
}

.feature-card {
  background-color: #ffffff !important;
  border-color: #e9ecef !important;
  text-align: center;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.feature-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 12px rgba(0,0,0,0.15);
}

.feature-icon {
  font-size: 2.5rem;
  color: #007bff;
  margin-bottom: 20px;
}

.feature-card h3 {
  color: #333333;
  margin-bottom: 10px;
}

.feature-card p {
  color: #666666;
}

/* 数据统计 */
.stats-section {
  padding: 80px 0;
  background-color: #ffffff;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 30px;
}

.stat-card {
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%) !important;
  border: 1px solid #e9ecef !important;
  border-radius: 16px !important;
  text-align: center;
  padding: 40px 20px;
  box-shadow: 0 8px 24px rgba(0,0,0,0.08);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.stat-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #007bff, #00bcd4);
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 30px rgba(0,0,0,0.12);
}

.stat-number {
  font-size: 3rem;
  font-weight: 700;
  color: #007bff;
  margin-bottom: 15px;
  font-family: 'Arial', sans-serif;
  letter-spacing: -1px;
  text-shadow: 0 2px 4px rgba(0,0,0,0.05);
  transition: color 0.3s ease;
}

.stat-card:hover .stat-number {
  color: #0056b3;
}

.stat-label {
  font-size: 1.1rem;
  color: #666666;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

/* 添加图标的样式 */
.stat-icon {
  font-size: 2rem;
  margin-bottom: 20px;
  color: #007bff;
  opacity: 0.9;
  transition: all 0.3s ease;
}

.stat-card:hover .stat-icon {
  transform: scale(1.1);
  opacity: 1;
}

/* 最新动态 */
.updates-section {
  padding: 80px 0;
  background-color: #f8f9fa;
}

.updates-content {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 30px;
}

.updates-column {
  background-color: #ffffff;
  border-radius: 8px;
  padding: 20px;
  border: 1px solid #e9ecef;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.column-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  border-bottom: 1px solid #e9ecef;
  padding-bottom: 10px;
}

.column-header h3 {
  color: #333333;
  font-size: 1.2rem;
}

.view-more {
  color: #007bff;
  text-decoration: none;
  font-size: 0.9rem;
}

.view-more:hover {
  text-decoration: underline;
}

/* 政策文件列表 */
.policy-list, .news-list, .hot-videos-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.policy-item, .news-item {
  padding: 10px 0;
  border-bottom: 1px solid #e9ecef;
}

.policy-item:last-child, .news-item:last-child, .hot-video-item:last-child {
  border-bottom: none;
}

.policy-meta, .news-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.policy-id, .policy-date, .news-date {
  font-size: 0.8rem;
  color: #666666;
}

.policy-title, .news-title {
  color: #333333;
  font-size: 0.95rem;
  margin: 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-clamp: 2;
  overflow: hidden;
}

/* 热门视频列表 */
.hot-video-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 10px 0;
  border-bottom: 1px solid #e9ecef;
}

.rank-number {
  font-size: 1.2rem;
  font-weight: 600;
  color: #666666;
  min-width: 24px;
  text-align: center;
}

.rank-number.rank-1 {
  color: #dc3545;
}

.rank-number.rank-2 {
  color: #ffc107;
}

.rank-number.rank-3 {
  color: #28a745;
}

.hot-video-title {
  flex: 1;
  color: #333333;
  font-size: 0.95rem;
  margin: 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-clamp: 2;
  overflow: hidden;
}

.hot-video-stats {
  display: flex;
  gap: 10px;
  font-size: 0.8rem;
  color: #666666;
}

.hot-video-stats span {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* CTA区域 */
.cta-section {
  background: linear-gradient(135deg, #e9ecef 0%, #f8f9fa 100%);
  padding: 60px 0;
  margin-top: 40px;
}

.cta-content {
  text-align: center;
}

.cta-content h2 {
  font-size: 2rem;
  color: #333333;
  margin-bottom: 20px;
}

.cta-content p {
  font-size: 1.1rem;
  color: #666666;
  margin-bottom: 30px;
}

/* 查看更多按钮 */
.view-more-btn {
  display: block;
  margin: 20px auto 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .updates-content {
    flex-direction: column;
    grid-template-columns: 1fr;
  }
  
  .banner-content h1 {
    font-size: 2rem;
  }
  
  .banner-actions {
    flex-direction: column;
    align-items: center;
  }
  
  .features-grid {
    grid-template-columns: 1fr;
  }
  
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 480px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .banner-content h1 {
    font-size: 1.8rem;
  }
}
</style>